package com.juejin.www.controller;

import com.juejin.www.aspect.Log;
import com.juejin.www.aspect.Perm;
import com.juejin.www.model.DTO.AuditDTO;
import com.juejin.www.model.DTO.PageDTO;
import com.juejin.www.model.DTO.Result;
import com.juejin.www.model.DTO.UserDTO;
import com.juejin.www.model.VO.AuditVO;
import com.juejin.www.service.AdminService;
import com.juejin.www.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Jacky
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Perm(permission = "audit:read")
    @GetMapping
    public Result getAudits(@RequestParam Integer currentPage,@RequestParam Integer pageSize,@RequestParam Integer isAudited){
        log.info("获取审核列表");
        PageDTO<AuditVO> audits = adminService.getAudits(currentPage, pageSize,isAudited);
        return Result.success(audits);
    }

    @Perm(permission = "audit:read")
    @GetMapping("/isNotAudited")
    public Result getIsNotAuditedCount(){
        log.info("获取未审核数");
        Integer isNotAuditedCount = adminService.getIsNotAuditedCount();
        return Result.success(isNotAuditedCount);
    }

    @Log
    @Perm(permission = "audit:edit")
    @PutMapping
    public Result audit(@RequestBody AuditDTO auditDTO, @RequestHeader("token") String jwt){
        Integer id = JwtUtils.getIdByJWT(jwt);
        auditDTO.setAuditor(id);
        log.info("{}号管理员审核{}号申请",auditDTO.getAuditor(),auditDTO.getId());
        adminService.audit(auditDTO);
        return Result.success();
    }

    @Log
    @Perm(permission = "lock:add")
    @GetMapping("/{id}")
    public Result lockUser(@PathVariable Integer id){
        log.info("封禁{}号用户",id);
        adminService.lockUser(id);
        return Result.success();
    }

    @Log
    @Perm(permission = "lock:delete")
    @DeleteMapping("/{id}")
    public Result unlockUser(@PathVariable Integer id){
        log.info("解封{}号用户",id);
        adminService.unlockUser(id);
        return Result.success();
    }

    @Log
    @Perm(permission = "admin:add")
    @PostMapping
    public Result addAdmin(@RequestBody UserDTO userDTO){
        log.info("添加管理员{}",userDTO.getUsername());
        boolean bol = adminService.addAdmin(userDTO);
        if(bol){
            return Result.success();
        }else {
            return Result.error("用户名已存在");
        }
    }
}
